from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.models import User, VSession, FileStore
from software.models import SoftwareData, SoftwareVersion, SoftwareType
from user.dataCheck import DataCheck
import pdb, os, datetime

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def dataOperation(request, *args, **kwargs):
    """
        url    : /software/data/operate/
        method : POST

    :param request:
            token: data.token, //用户的秘钥
            dataId: data.dataId,//资料id
            operation: data.operation, //0：查看，1：删除，2：恢复 

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'materialUrl':null,//返回资料url

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    

    user = datacheck.getUser(requestParam['token'])
    company = user.company
    data = SoftwareData.objects.get(pk=requestParam['dataId'])
    file = data.file

    if requestParam['operation'] == '0':
        if user.userType == '3':
            downloads = SoftwareVersion.objects.filter(softwareVersion_data=data, isDownload=company)
            if downloads.exists():
                data = {
                    "code": 0,
                    "msg": "success",
                    'materialUrl': download(data.file.fileName, "material", data.file.filePath)[1],
                }
                logger_request.info(data)
                return JsonResponse(data)
            else:
                data = {
                    'code': 0,
                    'msg': 'limits error',
                }
                logger_request.info(data)
                return JsonResponse(data)
        else:
            data = {
                "code": 0,
                "msg": "success",
                'materialUrl': download(data.file.fileName, "material", data.file.filePath)[1],
            }
            logger_request.info(data)
            return JsonResponse(data)

    elif requestParam['operation'] == '1':
        data.isActive = False
        data.save()

    elif requestParam['operation'] == '2' and data.isActive == False:
        data.isActive = True
        data.save()
    else:
        data = {
            'code': 1,
            'msg': 'operation error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        'materialUrl': '',
    }
    logger_request.info(data)
    return JsonResponse(data)


def dataCheck(request, *args, **kwargs):
    """
        url    : /software/data/check/
        method : POST

    :param request:
            token: data.token, //用户的秘钥
            dataId: data.dataId,//资料id 
            verify: data.verify,//审核结果 0:通过；1：不通过
            dataResult:data.dataResult,//处理结果

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    data = SoftwareData.objects.get(pk=requestParam['dataId'])

    if userType == '2':
        if requestParam['verify'] == '0':
            data.dataCheckState = 1
            data.dataResult = 1
            data.save()
        elif requestParam['verify'] == '1':
            data.dataCheckState = 2
            data.dataResult = 2
            data.save()
        else:
            data = {
                'code': 1,
                'msg': 'verify error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def getTypeList(request, *args, **kwargs):
    """
        url    : /software/softwaretype/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'softwareTypeList':[{
                    'typeId':null,//战区id
                    'name':null,//战区名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    softwareTypeList = SoftwareType.objects.filter(isActive=True, softwareTypeState='1')
    if softwareTypeList.exists():
        totalNum = len(softwareTypeList)
        softwareTypeLists = []
        result = softwareTypeList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                           requestParam[
                                                                                                               'page'] *
                                                                                                           requestParam[
                                                                                                               'maxItem'])]

        for softwareType in result:
            softwareTypeList = {
                'typeId': softwareType.id,
                'name': softwareType.softwareType,
            }
            softwareTypeLists.append(softwareTypeList)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "softwareTypeList": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "softwareTypeList": softwareTypeLists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def dataUpdate(request, *args, **kwargs):
    '''
        url:'/software/data/update/',
            method:'post',
            inputData:{
                token:data.token,//
                dataId:data.dataId,//资料id
                fileId:data.fileId,//资料文件
            }

    '''
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])
    # pdb.set_trace()

    # uploadUser userType
    userType = user.userType

    if userType == '1':
        data = SoftwareData.objects.get(pk=requestParam['dataId'])
        if requestParam['fileId'] != None:
            file = FileStore.objects.get(pk=requestParam['fileId'])
            data.dataName = file.fileName
            data.file = file
            data.dataCheckState = 0
            nowTime = datetime.datetime.now()
            data.uploadTime = nowTime.strftime('%Y-%m-%d %H:%M:%S')
            data.save()
        elif requestParam['fileId'] == None:
            data.dataName = requestParam['materialName']
            data.dataCheckState = 0
            data.save()
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def deleteFile(request, *args, **kwargs):
    '''
        url:'/software/deleteFile/',
            method:'post',
            inputData:{
                token:data.token,//
                dataId:data.dataId,//资料id
            }

    '''
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])

    # uploadUser userType
    userType = user.userType

    if userType == '1':
        data = SoftwareData.objects.get(pk=requestParam['id'])
        version = SoftwareVersion.objects.filter(pk=requestParam["versionId"])
        if requestParam['option'] == '0' and version.exists():
            for version in data.softwareVersion.filter(id=version[0].id):
                data.softwareVersion.remove(version)
            data.isActive = False
            data.save()
        elif requestParam['option'] == '1':
            pass
    else:
        data = {
            "code": 0,
            "msg": "userType erroe",
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)
